﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psm.Transport;
using Psm.Protocol;
using Psm.Messaging;
using Psm.Container;
using Psm.Client.Configuration;

namespace Psm.Client
{
    public class PsmClient
    {
        private IRemoteTransport transport;
        private IProtocol protocol;
        private IMessageFactory messageFactory;
        private ClientConfiguration configuration;
        private IMessageCallback messageCallback;

        public PsmClient(string configName, IMessageCallback messageCallback)
        {
            this.messageCallback = messageCallback;
            this.configuration = PsmClientConfiguration.GetConfiguration(configName);
            this.transport = Repository.GetInstance<IRemoteTransport>(this.configuration.Transport.Type, this.configuration.Transport.Composition);
            this.transport.Open();
            this.protocol = Repository.GetInstance<IProtocol>(this.configuration.Protocol.Type, this.configuration.Protocol.Composition);
            this.messageFactory = Repository.GetInstance<IMessageFactory>(this.configuration.Messaging.Type, this.configuration.Messaging.Composition);
            this.protocol.InitializeProtocol(this.transport, messageFactory);
            this.protocol.NewMessage += new EventHandler<NewMessageEventArgs>(NewMessageHandler);
            this.protocol.StartProcessing();
        }

        private void NewMessageHandler(object sender, NewMessageEventArgs args)
        {
            if(messageCallback != null ) messageCallback.NewMessage(args.Message);
        }

        public void SendMessage(IMessage message)
        {
            this.protocol.SendMessage(message);
        }

        public void Close()
        {
            this.transport.Close();
        }

        public void Flush()
        {
            this.protocol.Flush();
        }
    }
}
